# coding=utf-8
#
#
#       Copyright 2010 Dirk B. <dirkbo@googlemail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#
#

import os, re, urllib, urllib2, base64
import settings

class Zeit(object):
    def __init__(self):        
        self.username=settings.zeit_username
        self.password=settings.zeit_password
        self.email_sender= settings.email_sender
        self.email_user= settings.email_user
        self.email_passwd= settings.email_passwd
        self.email_server= settings.email_server
        self.email_port= settings.email_port
        self.email_recipient = settings.email_recipient
            
    def get_protected_page(self, theurl):
        req = urllib2.Request(theurl)
        try:
            handle = urllib2.urlopen(req)
        except IOError, e:
            # here we *want* to fail
            pass
        else:
            # If we don't fail then the page isn't protected
            print "This page isn't protected by authentication."
            sys.exit(1)

        if not hasattr(e, 'code') or e.code != 401:
            # we got an error - but not a 401 error
            print "This page isn't protected by authentication."
            print 'But we failed for another reason.'
            sys.exit(1)

        authline = e.headers['www-authenticate']
        # this gets the www-authenticate line from the headers
        # which has the authentication scheme and realm in it


        authobj = re.compile(
            r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''',
            re.IGNORECASE)
        # this regular expression is used to extract scheme and realm
        matchobj = authobj.match(authline)

        if not matchobj:
            # if the authline isn't matched by the regular expression
            # then something is wrong
            print 'The authentication header is badly formed.'
            print authline
            sys.exit(1)

        scheme = matchobj.group(1)
        realm = matchobj.group(2)
        # here we've extracted the scheme
        # and the realm from the header
        if scheme.lower() != 'basic':
            print 'This example only works with BASIC authentication.'
            sys.exit(1)

        base64string = base64.encodestring(
                        '%s:%s' % (self.username, self.password))[:-1]
        authheader =  "Basic %s" % base64string
        req.add_header("Authorization", authheader)
        try:
            handle = urllib2.urlopen(req)
        except IOError, e:
            # here we shouldn't fail if the username/password is right
            print "It looks like the username or password is wrong."
            sys.exit(1)
        thepage = handle.read()
        return thepage
        
    def downloadepub(self):
        print "Downloading .epub"
        secondpage= self.get_protected_page("https://premium.zeit.de/premium/cgi-bin/_er_member/p4z.fpl?ER_Do=createToken&Abo_RedirectTo=epaper.zeit.de/index_premium.php&user=dirkbo&aboxnr=871")
        #ePub-Download-re
        #http://contentserver.hgv-online.de/nodrm/fulfillment.{10,200}(?="><s)
        epub = re.findall('http://contentserver.hgv-online.de/nodrm/fulfillment.{10,200}(?="><s)', secondpage)
        if epub:
            if len(epub) > 0:
                epfile = urllib.URLopener()
                epfile.retrieve(epub[0], "die_zeit.epub")
            else:
                print "No Download-File found!"
        else:
            print "No Download-File found!"
        print "Done"
        
    def convertepub2mobi(self):
        print "Converting to .mobi..."
        command_line = 'ebook-convert die_zeit.epub die_zeit.mobi --output-profile kindle'
        os.system(command_line)
        print "Done!"
        
    def sendmobi(self):
        print "Sending E-Mail ...."
        command_line = 'calibre-smtp %(sender)s -r %(server)s -u %(user)s -p %(password)s --port %(port)s -vv %(recipient)s -a die_zeit.mobi "Die aktuelle Ausgabe der ZEIT"' % {'sender':self.email_sender, 'server':self.email_server, 'user': self.email_user, 'password': self.email_passwd, 'port': self.email_port, 'recipient' : self.email_recipient}
        os.system(command_line)
        print "Done!"
    
def main():
    z = Zeit()
    z.downloadepub()
    z.convertepub2mobi()
    z.sendmobi()
    return 0

if __name__ == '__main__':
    main()
